package com.jiandian.service.impl;

import com.jiandian.configration.OssConfig;
import com.jiandian.consts.BannerConsts;
import com.jiandian.entity.GameInfo;
import com.jiandian.service.GameInfoService;
import com.jiandian.service.OssService;
import com.jiandian.util.OssPathUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lik
 */
@Slf4j
@Service
public class OssServiceImpl implements OssService {

    @Autowired
    private OssConfig ossConfig;
    @Autowired
    private COSClient cosClient;

    @Autowired
    private GameInfoService gameInfoService;

    @Override
    public String getWholeUrl(String key) {
        return new StringBuilder(ossConfig.getDomain()).append(key).toString();
    }

    @Override
    public String getTextContent(String bucketName, String key) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
        COSObject cosObject = null;
        // 可能会出现文件不存在的情况
        try {
            cosObject = cosClient.getObject(getObjectRequest);
        } catch (CosServiceException exception) {
            log.error(exception.getMessage());
            return "";
        }
        COSObjectInputStream cosObjectInput = cosObject.getObjectContent();
        return getStreamString(cosObjectInput);
    }

    @Override
    public String getRealGameName(String bucketName, String dirName) {
        String key = OssPathUtil.getRealGameNameKey(dirName);
        return getTextContent(bucketName, key);
    }

    @Override
    public String getContext(String bucketName, String dirName) {
        String key = OssPathUtil.getContextKey(dirName);
        return getTextContent(bucketName, key);
    }

    @Override
    public String getDetailText(String bucketName, String dirName) {
        String key = OssPathUtil.getTextKey(dirName);
        return getTextContent(bucketName, key);
    }

    /**
     * 将流转为字符串
     *
     * @param tInputStream
     * @return
     */
    private static String getStreamString(InputStream tInputStream) {

        if (tInputStream != null) {
            try {
                BufferedReader tBufferedReader = new BufferedReader(new InputStreamReader(tInputStream));
                StringBuffer tStringBuffer = new StringBuffer();
                String sTempOneLine = "";
                while ((sTempOneLine = tBufferedReader.readLine()) != null) {
                    tStringBuffer.append(sTempOneLine);
                }
                return tStringBuffer.toString();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }


    @Override
    public String getLogoUrl(String bucketName, String dirName) {
        String logoKey = OssPathUtil.getLogoKey(dirName);
        return getWholeUrl(logoKey);
    }


    @Override
    public String getApkUrl(String bucketName, String dirName) {
        String apkKey = OssPathUtil.getApkKey(dirName);
        return getWholeUrl(apkKey);
    }

    @Override
    public String getImgsUrl(String bucketName, String prefix) {
        prefix += "/img/";
        List<COSObjectSummary> cosObjectSummaries = listDir(bucketName, prefix);
        return joinImgsUrl(cosObjectSummaries);
    }

    @Override
    public String getBannerUrls(String bucketName) {
        String prefix = BannerConsts.BANNER_DIR_NAME + "/";
        List<COSObjectSummary> cosObjectSummaries = listDir(bucketName, prefix);
        return joinImgsUrl(cosObjectSummaries);
    }

    @Override
    public List<COSObjectSummary> listDir(String bucketName, String prefix) {
        return listDir(bucketName, prefix, true);
    }

    @Override
    public List<COSObjectSummary> listDir(String bucketName, String prefix, boolean ifExceptDir) {
        List<COSObjectSummary> list = new ArrayList<>();
        try {
            ListObjectsRequest listObjectsRequest = null;


            String nextMarker = "";
            // 判断是否已经 list 完, 如果 list 结束, 则 isTruncated 为 false, 否则为 true
            boolean isTruncated = true;
            while (isTruncated) {
                listObjectsRequest = new ListObjectsRequest();
                listObjectsRequest.setMarker(nextMarker);
                listObjectsRequest.setBucketName(bucketName);
                // 设置 list 的 prefix, 表示 list 出来的文件 key 都是以这个 prefix 开始
                listObjectsRequest.setPrefix(prefix);
                // 设置 delimiter 为/, 即获取的是直接成员，不包含目录下的递归子成员
                if (ifExceptDir) {
                    listObjectsRequest.setDelimiter("/");
                }
                // 设置 marker, (marker 由上一次 list 获取到, 或者第一次 list marker 为空)
                //todo 这里在大于1000个时，需要再遍历，然后将结果加入集合
                // 设置最多 list 100个成员,（如果不设置, 默认为1000个，最大允许一次 list 1000个 key）
                listObjectsRequest.setMaxKeys(1000);
                listObjectsRequest.setEncodingType("url");
                ObjectListing objectListing = cosClient.listObjects(listObjectsRequest);
                // 获取下次 list 的 marker
                nextMarker = objectListing.getNextMarker();
                List<COSObjectSummary> objectSummaries = objectListing.getObjectSummaries();
                list.addAll(objectSummaries);

                isTruncated = objectListing.isTruncated();
            }


        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return list;
    }

    @Override
    public String getSelfApkUrl(String bucketName) {
        String prefix = BannerConsts.APK_DIR_NAME + "/";
        List<COSObjectSummary> cosObjectSummaries = listDir(bucketName, prefix);
        return joinImgsUrl(cosObjectSummaries);
    }

    private String joinImgsUrl(List<COSObjectSummary> objectSummaries) {
        StringBuilder imgsBuilder = new StringBuilder();

        for (COSObjectSummary cosObjectSummary : objectSummaries) {
            if (cosObjectSummary.getSize() == 0L) {
                continue;
            }
            imgsBuilder.append(getWholeUrl(cosObjectSummary.getKey())).append(";");
        }
        return imgsBuilder.toString();
    }


}
